// 简化的音频服务

export class AudioService {
  constructor() {
    this.audioContext = null
    this.currentAudio = null
    this.isPlaying = false
    this.currentMessageId = null

    // 流式播放
    this.streamQueues = new Map()
    this.onPlayEnd = null
    
    this.initAudioContext()
  }

  // 初始化AudioContext
  initAudioContext() {
    try {
      this.audioContext = new (window.AudioContext || window.webkitAudioContext)()
      
      // 简单的用户交互激活
      const activate = () => {
        if (this.audioContext.state === 'suspended') {
          this.audioContext.resume()
        }
        document.removeEventListener('click', activate, {once: true})
      }
      document.addEventListener('click', activate, {once: true})
    } catch (error) {
      console.error('音频初始化失败:', error)
    }
  }

  // 播放URL音频
  async playAudio(audioUrl, messageId = null) {
    this.stopAudio()
    if (!audioUrl) return

    this.currentAudio = new Audio(audioUrl)
    this.currentMessageId = messageId
    this.isPlaying = true

    this.currentAudio.onended = () => {
      this.isPlaying = false
      this.currentMessageId = null
      if (this.onPlayEnd) this.onPlayEnd(messageId)
    }
    this.currentAudio.onerror = () => {
      this.isPlaying = false
      if (this.onPlayEnd) this.onPlayEnd(messageId)
    }
    
    try {
      await this.currentAudio.play()
    } catch (error) {
      this.isPlaying = false
      throw error
    }
  }

  stopAudio() {
    // 停止传统音频
    if (this.currentAudio) {
      this.currentAudio.pause()
      this.currentAudio = null
    }
    
    // 停止所有流式音频
    this.streamQueues.forEach(queue => {
      if (queue.currentSource) {
        try { queue.currentSource.stop() } catch(e) {}
      }
      queue.buffers = []
    })
    
    this.isPlaying = false
    this.currentMessageId = null
  }

  // 处理流式音频数据
  async processAudioChunk(base64Data, messageId) {
    if (!this.audioContext) return
    
    // 激活AudioContext（如果被暂停）
    if (this.audioContext.state === 'suspended') {
      await this.audioContext.resume()
    }

    try {
      // 解码音频
      const buffer = this.base64ToBuffer(base64Data)
      const audioBuffer = await this.audioContext.decodeAudioData(buffer)
      
      // 初始化队列
      if (!this.streamQueues.has(messageId)) {
        this.streamQueues.set(messageId, {
          buffers: [],
          currentSource: null,
          nextStartTime: 0
        })
      }
      
      const queue = this.streamQueues.get(messageId)
      queue.buffers.push(audioBuffer)
      
      // 开始播放（如果还没开始）
      if (!queue.currentSource) {
        this.playNextBuffer(messageId)
      }
    } catch (error) {
      console.error('音频处理失败:', error)
    }
  }

  // Base64转Buffer
  base64ToBuffer(base64) {
    const binary = atob(base64)
    const bytes = new Uint8Array(binary.length)
    for (let i = 0; i < binary.length; i++) {
      bytes[i] = binary.charCodeAt(i)
    }
    return bytes.buffer
  }

  // 播放队列中的下一个音频块
  playNextBuffer(messageId) {
    const queue = this.streamQueues.get(messageId)
    if (!queue || queue.buffers.length === 0) {
      // 等一下看是否有更多数据
      setTimeout(() => {
        const updatedQueue = this.streamQueues.get(messageId)
        if (updatedQueue && updatedQueue.buffers.length > 0) {
          this.playNextBuffer(messageId)
        } else {
          // 播放结束
          this.streamQueues.delete(messageId)
          if (this.currentMessageId === messageId) {
            this.isPlaying = false
            this.currentMessageId = null
          }
          if (this.onPlayEnd) this.onPlayEnd(messageId)
        }
      }, 100)
      return
    }

    const buffer = queue.buffers.shift()
    const source = this.audioContext.createBufferSource()
    source.buffer = buffer
    source.connect(this.audioContext.destination)
    
    queue.currentSource = source
    this.isPlaying = true
    this.currentMessageId = messageId

    // 计算播放时间，确保连续播放
    const now = this.audioContext.currentTime
    const startTime = Math.max(now, queue.nextStartTime)
    
    source.start(startTime)
    queue.nextStartTime = startTime + buffer.duration

    source.onended = () => {
      queue.currentSource = null
      this.playNextBuffer(messageId) // 继续播放下一个
    }
  }

  // 停止指定消息的流式播放
  stopStream(messageId) {
    const queue = this.streamQueues.get(messageId)
    if (queue) {
      if (queue.currentSource) {
        try { queue.currentSource.stop() } catch(e) {}
      }
      queue.buffers = []
      this.streamQueues.delete(messageId)
    }
    
    if (this.currentMessageId === messageId) {
      this.isPlaying = false
      this.currentMessageId = null
    }
  }

  isPlayingMessage(messageId) {
    return this.currentMessageId === messageId && this.isPlaying
  }
}

export const audioService = new AudioService()